package com.hhp.cloud.shop.gateway.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.hhp.cloud.shop.common.core.enums.BizCodeEnume;
import com.hhp.cloud.shop.common.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: sentinel限流回调
 * @author: hhp
 * @date: 2021/12/3 14:39
 */
@Configuration
@Slf4j
public class SentinelGatewayConfig {
    public SentinelGatewayConfig(){
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //网关限流 调用此回调
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                log.info("网关限流...当前请求:{}", serverWebExchange.getRequest().getPath().toString());
                R error = R.error(BizCodeEnume.TOO_MANY_REQUEST);
                String errorJson = JSONUtil.toJsonStr(error);
                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errorJson), String.class);
                return body;
            }
        });
    }
}
